package com.fixme4trade.view;

import java.util.Date;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;

import br.gov.frameworkdemoiselle.DemoiselleException;
import br.gov.frameworkdemoiselle.annotation.Name;
import br.gov.frameworkdemoiselle.annotation.NextView;
import br.gov.frameworkdemoiselle.annotation.PreviousView;
import br.gov.frameworkdemoiselle.security.SecurityContext;
import br.gov.frameworkdemoiselle.stereotype.ViewController;
import br.gov.frameworkdemoiselle.template.AbstractEditPageBean;
import br.gov.frameworkdemoiselle.template.AbstractPageBean;
import br.gov.frameworkdemoiselle.transaction.Transactional;
import br.gov.frameworkdemoiselle.util.Parameter;

import com.fixme4trade.business.ProductBC;
import com.fixme4trade.business.SellBC;
import com.fixme4trade.business.UserBC;
import com.fixme4trade.domain.Customer;
import com.fixme4trade.domain.Product;
import com.fixme4trade.domain.Sell;
import com.fixme4trade.template.DelegateEditPageBean;

@ViewController
@PreviousView("/public/product_show.xhtml")
@NextView("/auth/shopping_cart.xhtml")
public class SellMB extends AbstractPageBean {

	private static final long serialVersionUID = 1L;

	@Inject
	@Name("productId")
	private Parameter<Long> productIdParameter;

	@Inject
	private SellBC bc;

	@Inject
	private ProductBC productBC;

	@Inject
	private UserBC userBC;
	
	@Inject
	private SecurityContext context;
	
	@Inject
	@Name("sellId")
	Parameter<Long> sellId;
	
	private int quantity = 1;
					
	@Transactional
	public String sellProduct(Product product) {
		Long productId = productIdParameter.getValue();
		System.out.println("Product ID Parameter = "+productId);
		//Product product = productBC.load(productId);
		
		if (!context.isLoggedIn()) {
			System.out.println("redirecionar p/ login");
			return "/public/login.jsf?fwd=/public/product_show?id="+product.getId();
		} else {
			Customer customer = userBC.getAuthenticatedCustomer();
			
			if (customer == null) {
				System.out.println("!!! CUSTOMER == NULL!");
				return "/public/index.jsf";
			}

			bc.sellProduct(product, customer, quantity);
			
			return super.getNextView();
		}		
		
	}
			
	public int getQuantity() {
		return quantity;
	}
	
	public void setQuantity (int quantity) {
		this.quantity = quantity;
	}		

	public double getEstimatedPrice(Product product) {
		return quantity * product.getPrice();
	}

	public void increaseQuantity(Product product) {
		//Long productId = productIdParameter.getValue();
		
		//Product product = productBC.load(productId);
		if (quantity < product.getQuantity())
			quantity++;
	}

	public void decreaseQuantity() {				
		if (quantity != 1) {
			quantity--;
		}
	}
	
	@Transactional
	public String doPayment() {
		System.out.println("SellID (2) = "+sellId.getValue());
		return "/auth/index.xhtml";
	}
}
